import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import {
  Row, Col, Card, Form, Input, Radio, Select, Icon, Button, Upload, List, Modal, message, Badge, TreeSelect, Tag, InputNumber, Spin, Popover,
} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './ParentRecomm.less';
import ChannelModal from 'components/Content/ChannelModal';

import { routerRedux } from 'dva/router';
import ParentLayout from 'components/Content/ParentLayout';
import LayoutTypeModal from 'components/Content/ParentLayoutTypeModal';

import LayoutDetail1 from './ParentLayoutDetail1';
import LayoutDetail2 from './ParentLayoutDetail2';
import LayoutDetail3 from './ParentLayoutDetail3';
import Adv from './Adv';
var _ = require('lodash');

const FormItem = Form.Item;

@connect(({ parentRecomm, loading }) => ({
  parentRecomm,
  channelTree: parentRecomm.channelTree,
  goodsList: parentRecomm.goodsList,
  loading: loading.models.parentRecomm,
}))
@Form.create()
export default class AppRecommPage extends PureComponent {
  state = {
    modalVisible: false,
    channelModal: false,
    record: null,
    layoutList: [],
    layoutList1: [],
    layoutList2: [],
    layoutList3: [],
    layoutList4: [],


    dealedList: [],


    weight: null,
    current: null,  //当前正在添加的数组下标

    layoutType: null,
    layoutDetail: null,

    appType: null,

    advType: null,

    //广告相关
    adv: null,
    editType: null,

    recommChannelList: [],

    hadChannelList: [],

    currentChannel: null,

    clickChannel: null,
  };

  componentDidMount() {
    // if (this.props.match.params.recommId != 'new') {
    //   this.props.dispatch({
    //     type: 'parentRecomm/fetchRecommPage',
    //     payload: { recommId: this.props.match.params.recommId },
    //     callback: (data) => this._setRecord(data)
    //   })
    // }
    this._search();
    this.props.dispatch({
      type: 'parentRecomm/fetchChannelTree',
      payload: {},
    });

    // this.props.dispatch({
    //   type: 'parentRecomm/fetch',
    //   payload: { recommId: this.props.match.params.recommId },
    //   callback: (data) => this._setRecord(data)
    // })

  }

  _search() {
    this.props.dispatch({
      type: 'parentRecomm/fetch',
      payload: { recommId: this.props.match.params.recommId },
      callback: (data) => this._setRecord(data)
    })
  }

  componentWillReceiveProps(nextProps) {
    // alert(1)
  }

  _advSearch() {
    this.props.dispatch({
      type: 'parentRecomm/fetchAdv',
      payload: { advType: this.state.advType },
      callback: (data) => this._setAdv(data)
    });
  }

  _setAdv(data) {
    this.setState({ adv: data })
  }

  _goodsSearch(filedValue) {
    this.props.dispatch({
      type: 'parentRecomm/fetchGoodsList',
      payload: filedValue,
    });
  }

  //分组
  _groupBy(array, f) {
    // debugger;
    const groups = {};
    array.forEach(function (o) {
      const group = JSON.stringify(f(o));
      groups[group] = groups[group] || [];
      groups[group].push(o);
    });
    return Object.keys(groups).map(function (group) {
      return groups[group];
    });
  }


  _setRecord(data) {
    this.setState({ advType: data.recommInfo.appType, appType: data.recommInfo.appType })
    this._advSearch(data.recommInfo.appType);
    console.log('设置-----------------', data)
    let hadChannelList = [];
    if (data.recommChannelList && data.recommChannelList.length > 0) {
      for (let i = 0; i < data.recommChannelList.length; i++) {
        hadChannelList.push('' + data.recommChannelList[i].channelId)
      }
    }

    console.log('设置hadChannelList-----------------', hadChannelList)

    this.setState({
      record: data,
      layoutList: data.layoutList,
      dealedList: data.recommChannelList,
      layoutDetail: null,
      hadChannelList: hadChannelList,
    })
  }

  _addFristLayout(clickChannel) {
    this.setState({ weight: 1000, current: 0, appType: this.state.appType, clickChannel: clickChannel })
    this._setModalVisible(true)
  }

  _addLayout(item, i, type, clickChannel) {
    console.log(i, type)
    let { record, layoutList1, layoutList2, layoutList3, layoutList4 } = this.state;
    let weight = null;

    if ((i + 1) == item.length) {  //点击最后一项的添加布局
      weight = item[i].weight + 1000;
    } else if ((i + 1) < (item.length)) {  //点击中间的
      weight = parseInt((item[i].weight + item[i + 1].weight) / 2)
    }

    console.log('要添加的权重', weight)

    this.setState({ weight: weight, current: i + 1, appType: this.state.appType, clickChannel: clickChannel })

    this._setModalVisible(true)
  }

  _setModalVisible(flag) {
    this.setState({ modalVisible: flag })
  }

  _chooseType(type) {
    this.props.dispatch({
      type: 'parentRecomm/addRecommPageLayout',
      payload: { recommId: this.props.match.params.recommId, layoutStyle: type, weight: this.state.weight, appType: this.state.appType, channelId: this.state.clickChannel },
      callback: () => this._addLayoutBack()
    })
  }

  _addLayoutBack() {
    this.setState({
      modalVisible: false,
      weight: null,
      current: null,
      appType: null,
    })
    this._search()
  }

  _deleteLayout(item, i) {
    this.props.dispatch({
      type: 'parentRecomm/deletePageLayout',
      payload: { layoutId: item.layoutId },
      callback: () => this._search()
    })
  }

  _editLayout(item, i) {
    console.log('布局详情', item)
    this.setState({ layoutDetail: item, editType: 'detail' })
  }

  _forwardLayout(oldList, i, channelI, type) {
    console.log('oldListoldList-----------', oldList)
    if (i == 0) return;
    let dealedList = _.cloneDeep(this.state.dealedList);

    let before = oldList[(i - 1)];
    let click = oldList[i];

    let newList = [];
    for (let j = 0; j < oldList.length; j++) {
      if (j == (i - 1)) {
        newList.push(click)
      } else if (j == i) {
        newList.push(before)
      } else {
        newList.push(oldList[j])
      }
    }

    if (newList && (newList.length > 0)) {
      let list = [];
      for (let k = 0; k < newList.length; k++) {
        let one = newList[k];
        one.weight = (k + 1) * 1000;
        list.push(one)
      }
      newList = list;
    }
    let newDealedList = []
    if (dealedList && dealedList.length > 0) {
      for (let b = 0; b < dealedList.length; b++) {
        newDealedList.push(dealedList[b])
      }
    }

    console.log('newList-----------', newList)

    newDealedList[channelI]['layoutList'] = newList;
    this.setState({ dealedList: newDealedList })
  }

  _backLayout(oldList, i, channelI, type) {
    console.log('iiiiiiiiiiiiiii', i)
    if (i == oldList.length) return;
    let dealedList = this.state.dealedList;
    // let oldList = this.state.layoutList;
    console.log('老的数组》》》》》》》》》', oldList)

    let after = oldList[(i + 1)];
    let click = oldList[i];

    let newList = [];
    for (let j = 0; j < oldList.length; j++) {
      if (j == (i)) {
        newList.push(after)
      } else if (j == (i + 1)) {
        newList.push(click)
      } else {
        newList.push(oldList[j])
      }
    }
    if (newList && (newList.length > 0)) {
      let list = [];
      for (let k = 0; k < newList.length; k++) {
        let one = newList[k];
        one.weight = (k + 1) * 1000;
        list.push(one)
      }
      newList = list;
    }

    let newDealedList = []
    if (dealedList && dealedList.length > 0) {
      for (let b = 0; b < dealedList.length; b++) {
        newDealedList.push(dealedList[b])
      }
    }
    newDealedList[channelI]['layoutList'] = newList;
    this.setState({ dealedList: newDealedList })
  }

  _savePage() {
    console.log('最终保存数据', this.state.record)
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      let values = {};
      values['recommId'] = this.state.record.recommInfo.recommId;
      values['appType'] = this.state.record.recommInfo.appType;
      values['recommName'] = fieldsValue.recommName;

      let list = []

      let dealedList = this.state.dealedList;
      console.log('布局数据-----------', dealedList)
      if (dealedList && dealedList.length > 0) {
        for (let i = 0; i < dealedList.length; i++) {
          let oneChannelData = dealedList[i];
          // if (oneChannelData && oneChannelData.layoutList.length > 0) {
          console.log('oneChannelData>>>>>>>>>>>', oneChannelData)
          for (let k = 0; k < oneChannelData.layoutList.length; k++) {
            let one = oneChannelData.layoutList[k];
            let newOne = {};
            newOne['layoutStyle'] = one.layoutStyle;
            newOne['channelId'] = one.channelId;
            newOne['appType'] = one.appType;
            newOne['layoutId'] = one.layoutId;
            newOne['weight'] = (k + 1) * 1000;
            list.push(newOne)
          }
          // } else {
          //   message.error('频道布局不能为空')
          // }
        }
      }

      values['layoutList'] = list;

      console.log('listlistlistlistlistlistlist', list)

      this.props.dispatch({
        type: 'parentRecomm/editPageLayout',
        payload: values,
        callback: () => this._search()
      })
    })
  }

  _addChannel(index) {
    this.setState({ currentChannel: index })
    this._setChannelModal(true);
  }

  _setChannelModal(flag) {
    if (flag == false) {
      this.setState({ currentChannel: null })
    }
    this.setState({ channelModal: flag })
  }

  _commitChannel(channelId) {
    this._setChannelModal(false)

    let list = _.cloneDeep(this.state.dealedList);

    console.log('原来的数据---------------------------', list, this.state.currentChannel)

    let add = {}

    let newList = [];
    let submitList = [];

    if (!(list && list.length > 0)) {
      add['recommId'] = this.props.match.params.recommId;
      add['channelId'] = channelId;
      add['weight'] = 1000;
      newList.push(add)
    } else {
      // for (let i = 0; i < (list.length + 1); i++) {
      //   let one = _.cloneDeep(list[i])
      //   console.log('原来的数据---------------------------oneone', one)
      //   if ((this.state.currentChannel + 1) == i) {
      //     let newOne = {};
      //     newOne['recommId'] = this.props.match.params.recommId;
      //     newOne['channelId'] = channelId;
      //     newOne['weight'] = (i + 1) * 1000;
      //     newList.push(newOne)
      //   } else {
      //     let newOne = {};
      //     newOne['recommId'] = one.recommId;
      //     newOne['channelId'] = one.channelId;
      //     newOne['weight'] = (i + 1) * 1000;
      //     newList.push(newOne)
      //   }
      // }currentChannel
      newList = _.cloneDeep(this.state.dealedList)
      let newOne = {}
      newOne['recommId'] = this.props.match.params.recommId;
      newOne['channelId'] = channelId;
      newOne['weight'] = 1000;
      newList.splice((this.state.currentChannel + 1), 0, newOne);
    }

    for (let i = 0; i < newList.length; i++) {
      let oldOne = _.cloneDeep(newList[i]);
      delete oldOne.layoutList;
      delete oldOne.channelName;
      oldOne.weight = (i + 1) * 1000;
      submitList.push(oldOne)
    }

    console.log('提交的list-----------', submitList)

    if (submitList && submitList.length > 0) {
      for (let j = 0; j < submitList.length; j++) {
        if ((this.state.currentChannel + 1) == j) {
          if (j == (submitList.length - 1)) {
            //添加频道
            this.props.dispatch({
              type: 'parentRecomm/add',
              payload: submitList[j],
              callback: () => this._search()
            })
          } else {
            //添加频道
            this.props.dispatch({
              type: 'parentRecomm/add',
              payload: submitList[j],
              // callback: () => this._search()
            })
          }

        } else {
          if (j == (submitList.length - 1)) {
            //修改频道
            this.props.dispatch({
              type: 'parentRecomm/update',
              payload: submitList[j],
              callback: () => this._search()
            })
          } else {
            //修改频道
            this.props.dispatch({
              type: 'parentRecomm/update',
              payload: submitList[j],
              // callback: () => this._search()
            })
          }
        }
      }
    }
  }

  _deleteChannel(item) {
    this.props.dispatch({
      type: 'parentRecomm/del',
      payload: { recommId: this.props.match.params.recommId, channelId: item.channelId },
      callback: () => this._search()
    })
  }

  _forwardChannel(item, i) {
    if (i == 0) return;
    let oldList = _.cloneDeep(this.state.dealedList);
    let before = oldList[(i - 1)];
    let click = oldList[i];
    let newList = [];
    for (let j = 0; j < oldList.length; j++) {
      if (j == (i - 1)) {
        newList.push(click)
      } else if (j == i) {
        newList.push(before)
      } else {
        newList.push(oldList[j])
      }
    }
    if (newList && (newList.length > 0)) {
      let list = [];
      for (let k = 0; k < newList.length; k++) {
        let one = newList[k];
        one.weight = (k + 1) * 1000;
        list.push(one)
      }
      newList = list;
    }
    let newDealedList = []
    if (newList && newList.length > 0) {
      for (let b = 0; b < newList.length; b++) {
        newDealedList.push(newList[b])
      }
    }

    console.log('newList-----------', newDealedList)
    this.setState({ dealedList: newDealedList })

    let submitList = [];
    for (let i = 0; i < newDealedList.length; i++) {
      let oldOne = _.cloneDeep(newDealedList[i]);
      delete oldOne.layoutList;
      delete oldOne.channelName;
      oldOne.weight = (i + 1) * 1000;
      submitList.push(oldOne)
    }

    for (let j = 0; j < submitList.length; j++) {
      if (j == (submitList.length - 1)) {
        //修改频道
        this.props.dispatch({
          type: 'parentRecomm/update',
          payload: submitList[j],
          // callback: () => this._search()
        })
      } else {
        //修改频道
        this.props.dispatch({
          type: 'parentRecomm/update',
          payload: submitList[j],
          // callback: () => this._search()
        })
      }
    }
  }

  _backChannel(item, i) {
    let oldList = _.cloneDeep(this.state.dealedList);
    if (i == oldList.length) return;
    let after = oldList[(i + 1)];
    let click = oldList[i];

    let newList = [];
    for (let j = 0; j < oldList.length; j++) {
      if (j == (i)) {
        newList.push(after)
      } else if (j == (i + 1)) {
        newList.push(click)
      } else {
        newList.push(oldList[j])
      }
    }
    if (newList && (newList.length > 0)) {
      let list = [];
      for (let k = 0; k < newList.length; k++) {
        let one = newList[k];
        one.weight = (k + 1) * 1000;
        list.push(one)
      }
      newList = list;
    }
    let newDealedList = []
    if (newList && newList.length > 0) {
      for (let b = 0; b < newList.length; b++) {
        newDealedList.push(newList[b])
      }
    }

    this.setState({ dealedList: newDealedList })


    let submitList = [];
    for (let i = 0; i < newDealedList.length; i++) {
      let oldOne = _.cloneDeep(newDealedList[i]);
      delete oldOne.layoutList;
      delete oldOne.channelName;
      oldOne.weight = (i + 1) * 1000;
      submitList.push(oldOne)
    }

    for (let j = 0; j < submitList.length; j++) {
      if (j == (submitList.length - 1)) {
        //修改频道
        this.props.dispatch({
          type: 'parentRecomm/update',
          payload: submitList[j],
          // callback: () => this._search()
        })
      } else {
        //修改频道
        this.props.dispatch({
          type: 'parentRecomm/update',
          payload: submitList[j],
          // callback: () => this._search()
        })
      }
    }
  }

  _renderChannel(item, channelI) {
    // console.log('每一个channel=================item', item)
    const content = (
      <div className={styles.buttonContainer}>
        <button onClick={() => this._editChannel(item)}>编辑</button>
        <button disabled={channelI == 0 ? true : false} onClick={() => this._forwardChannel(item, channelI)}>上移</button>
        <button disabled={(channelI + 1) == this.state.dealedList.length ? true : false} onClick={() => this._backChannel(item, channelI)}>下移</button>
        <button onClick={() => this._addChannel(channelI)}>添加频道</button>
        <button onClick={() => this._deleteChannel(item)}>删除</button>
      </div>
    )
    return (
      <div key={channelI}>
        <Popover content={content}>
          <div className={styles.channelText}>{item.channelName}</div>
        </Popover>

        <div className={styles.layoutContainer}>
          {item && item.layoutList && (item.layoutList.length > 0) ?
            item.layoutList.map((oneLayout, i) => {
              // console.log('oneLayoutoneLayoutoneLayout----', item)
              return (
                <ParentLayout item={oneLayout} key={oneLayout.layoutId} first={item.layoutList[0].weight} last={item.layoutList[item.layoutList.length - 1].weight}
                  editLayout={() => this._editLayout(oneLayout, channelI)}
                  forwardLayout={() => this._forwardLayout(item.layoutList, i, channelI, 1)}
                  backLayout={() => this._backLayout(item.layoutList, i, channelI, 1)}
                  addLayout={() => this._addLayout(item.layoutList, i, channelI, item.channelId)}
                  deleteLayout={() => this._deleteLayout(oneLayout, channelI)}
                />
              )
            })
            :
            <div style={{ display: 'flex', width: '375px', justifyContent: 'center', alignItems: 'center' }}>
              <Button type="primary" onClick={() => this._addFristLayout(item.channelId)}>添加布局</Button>
            </div>

          }
        </div>
      </div>
    )
  }


  render() {
    const { record, layoutList, layoutList1, layoutList2, layoutList3, layoutList4, layoutDetail } = this.state;
    const { form } = this.props;
    return (
      <PageHeaderLayout>
        <div className={styles.container}>
          <div className={styles.leftContainer}>
            <div className={styles.header}>
              {this.state.appType == "0" ? '精选' : this.state.appType == "1" ? '早教' : this.state.appType == "2" ? '绘本' : this.state.appType == "3" ? '卡通' : this.state.appType == "4" ? '儿歌故事' : ''}
            </div>

            <div className={styles.phoneContainer}>
              <div className={styles.advContainer}>
                运营位推荐
              <Button style={{ marginTop: '20px' }} type="primary" onClick={() => { this.setState({ editType: 'adv' }) }} >编辑</Button>
              </div>

              <div style={{ width: '355px', marginTop: '10px' }}>
                {(this.state.dealedList && this.state.dealedList.length > 0) ?
                  this.state.dealedList.map(
                    (item, i) => this._renderChannel(item, i)
                  )
                  :
                  <div>
                    <Button type="primary" onClick={() => this._addChannel(-1)}>添加频道</Button>
                  </div>

                }

                <div style={{ marginTop: '15px' }}>
                  <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} label="页面名称" >
                    {form.getFieldDecorator('recommName', {
                      initialValue: (record && record.recommInfo && record.recommInfo.recommName) ? record.recommInfo.recommName : null,
                      rules: [{ required: true, message: '请输入页面名称' }],
                    })(<Input placeholder="请输入页面名称" maxLength="10" />)}
                  </FormItem>
                  <FormItem>
                    <Button type="primary" onClick={() => this._savePage()}>保存</Button>
                    <Button type="primary" style={{ marginLeft: '30px' }} onClick={() => { this.props.dispatch(routerRedux.goBack()) }}>返回列表</Button>
                  </FormItem>
                </div>

              </div>

            </div>


          </div>

          <div className={styles.rightContainer}>
            {this.state.editType == 'adv' ?
              <Adv advDetailList={(this.state.adv && this.state.adv.advDetailList && (this.state.adv.advDetailList.length > 0) ? this.state.adv.advDetailList : [])} 
                advId={ (this.state.adv && this.state.adv.advInfo) ? this.state.adv.advInfo.advId : null}
                advOk={() => this._okAdv()} advCancel={() => this._advCancel()}
                advSearch={() => this._advSearch()} loading={this.props.loading}
              />
              :
              this.state.editType == 'detail' ?

                <div style={{ display: 'flex', flexDirection: 'column', justifyContent: "center", alignItems: 'center' }}>
                  {layoutDetail ?
                    ((layoutDetail.layoutStyle == '0')) ?
                      <div className={styles.editItem}>
                        <LayoutDetail1 layoutDetail={layoutDetail}
                          channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                          goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                          recommPageSearch={() => this._search()}
                        />
                      </div>
                      :
                      ((layoutDetail.layoutStyle == '1')) ?
                        <div className={styles.editItem2}>
                          <LayoutDetail2 layoutDetail={layoutDetail}
                            channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                            goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                            recommPageSearch={() => this._search()}
                          />
                        </div>
                        :
                        ((layoutDetail.layoutStyle == '2')) ?
                          <div className={styles.editItem3}>
                            <LayoutDetail3 layoutDetail={layoutDetail}
                              channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                              goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                              recommPageSearch={() => this._search()}
                            />
                          </div>
                          :
                          null
                    :
                    null
                  }
                  <div style={{ height: '100px' }}></div>
                </div>
                :

                null
            }

          </div>



          <LayoutTypeModal visible={this.state.modalVisible} chooseType={(type) => this._chooseType(type)}
            cancel={() => this._setModalVisible(false)}
          />

          <ChannelModal visible={this.state.channelModal} chooseType={(type) => this._chooseChannel(type)}
            cancel={() => this._setChannelModal(false)} channelList={this.props.channelTree}
            addChannel={(channelId) => this._commitChannel(channelId)} hadChannelList={this.state.hadChannelList}
          />

        </div>
      </PageHeaderLayout>
    )
  }
}